import pandas as pd
import numpy as np
from snownlp import SnowNLP
import matplotlib.pyplot as plt
import seaborn as sns
from datetime import datetime
import os
import matplotlib as mpl

# 设置中文字体
plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号

class SentimentAnalyzer:
    def __init__(self, data_path):
        """
        初始化情感分析器
        :param data_path: 预处理后的评论数据文件路径
        """
        self.data_path = data_path
        self.df = None
        self.sentiment_scores = None
        
    def load_data(self):
        """加载并预处理数据"""
        self.df = pd.read_csv(self.data_path)
        # 转换时间格式
        self.df['created_at'] = pd.to_datetime(self.df['created_at'])
        
    def analyze_sentiment(self):
        """进行情感分析"""
        print("开始情感分析...")
        self.sentiment_scores = []
        
        for text in self.df['cleaned_text']:
            try:
                s = SnowNLP(text)
                # 获取情感得分（0-1之间，越接近1表示越积极）
                score = s.sentiments
                self.sentiment_scores.append(score)
            except Exception as e:
                print(f"分析文本时出错: {e}")
                self.sentiment_scores.append(0.5)  # 出错时设为中性
                
        self.df['sentiment_score'] = self.sentiment_scores
        
    def classify_sentiment(self):
        """将情感得分分类为积极、中性和消极"""
        self.df['sentiment'] = pd.cut(
            self.df['sentiment_score'],
            bins=[0, 0.4, 0.6, 1],
            labels=['消极', '中性', '积极'],
            include_lowest=True
        )
        
    def analyze_sentiment_distribution(self):
        """分析情感分布"""
        sentiment_dist = self.df['sentiment'].value_counts(normalize=True)
        print("\n情感分布统计:")
        print(sentiment_dist)
        
        # 绘制情感分布饼图
        plt.figure(figsize=(8, 6))
        plt.pie(sentiment_dist, labels=sentiment_dist.index, autopct='%1.1f%%')
        plt.title('评论情感分布')
        plt.savefig('sentiment_distribution.png', dpi=300, bbox_inches='tight')
        plt.close()
        
    def analyze_sentiment_trend(self):
        """分析情感趋势"""
        # 按日期分组计算平均情感得分
        daily_sentiment = self.df.groupby(self.df['created_at'].dt.date)['sentiment_score'].mean()
        
        plt.figure(figsize=(12, 6))
        daily_sentiment.plot(kind='line')
        plt.title('情感趋势变化')
        plt.xlabel('日期')
        plt.ylabel('平均情感得分')
        plt.grid(True)
        plt.savefig('sentiment_trend.png', dpi=300, bbox_inches='tight')
        plt.close()
        
    def analyze_sentiment_correlation(self):
        """分析情感得分与互动指标的相关性"""
        correlation = self.df[['sentiment_score', 'like_counts', 'reply_counts']].corr()
        print("\n情感得分与互动指标的相关性:")
        print(correlation)
        
        # 绘制相关性热力图
        plt.figure(figsize=(8, 6))
        sns.heatmap(correlation, annot=True, cmap='coolwarm')
        plt.title('情感得分与互动指标相关性')
        plt.savefig('sentiment_correlation.png', dpi=300, bbox_inches='tight')
        plt.close()
        
    def save_results(self):
        """保存分析结果"""
        # 创建结果目录
        os.makedirs('analysis_results', exist_ok=True)
        
        # 保存情感分析结果
        self.df.to_csv('analysis_results/sentiment_analysis_results.csv', index=False)
        
        # 生成分析报告
        with open('analysis_results/sentiment_analysis_report.txt', 'w', encoding='utf-8') as f:
            f.write("情感分析报告\n")
            f.write("="*50 + "\n\n")
            
            f.write("1. 情感分布统计\n")
            f.write(str(self.df['sentiment'].value_counts(normalize=True)) + "\n\n")
            
            f.write("2. 情感得分统计\n")
            f.write(f"平均情感得分: {self.df['sentiment_score'].mean():.4f}\n")
            f.write(f"情感得分标准差: {self.df['sentiment_score'].std():.4f}\n\n")
            
            f.write("3. 情感与互动相关性\n")
            f.write(str(self.df[['sentiment_score', 'like_counts', 'reply_counts']].corr()) + "\n")
            
    def run_analysis(self):
        """运行完整的分析流程"""
        self.load_data()
        self.analyze_sentiment()
        self.classify_sentiment()
        self.analyze_sentiment_distribution()
        self.analyze_sentiment_trend()
        self.analyze_sentiment_correlation()
        self.save_results()
        print("\n情感分析完成！结果已保存到analysis_results目录。")

if __name__ == "__main__":
    # 使用示例
    analyzer = SentimentAnalyzer('../../weibo_spider/data_processing/preprocessed_comments.csv')
    analyzer.run_analysis() 